How to enable cors in ASP.NET Core 6.0 Web API project?
How to enable cors in ASP.NET Core 6.0 Web API project?
445
07-Nov-2023
Updated on 08-Nov-2023
Aryan Kumar
08-Nov-2023Enabling Cross-Origin Resource Sharing (CORS) in an ASP.NET Core 6.0 Web API project allows your API to respond to requests from different domains or origins. To enable CORS, you can follow these steps:
Install the Microsoft.AspNetCore.Cors Package (if not already installed):
Make sure you have the Microsoft.AspNetCore.Cors package added to your project. If it's not already included, you can add it using the following command:
Configure CORS in the Startup.cs File:
In your Startup.cs file, you need to configure CORS services in the ConfigureServices method and set up CORS policies in the Configure method.
csharpCopy code
In the code above:
Apply the CORS Policy:
To apply the CORS policy to your controllers or specific actions, you can use the [EnableCors] attribute:
In this example, the "AllowSpecificOrigin" CORS policy is applied to the Get action of the MyController.
With these configurations, your ASP.NET Core 6.0 Web API project is now set up to allow cross-origin requests from the specified domains. Be sure to customize the CORS policy to match your specific needs, such as allowing multiple origins, headers, or methods.